<template>
  <div class="wrapper">
    <div class="content">
      <el-form :inline="true">
        <el-form-item label="销售人员：">
          <el-tooltip class="item" effect="dark" :disabled="assessUsersName.length === 0" :content="assessUsersName" placement="bottom">
            <el-input style="width: 150px;" @click="selectDingUsers('assessUsers', 'assessUsersName')" placeholder="请选择人员" v-model="assessUsersName" :disabled="true"></el-input>
          </el-tooltip>
        </el-form-item>
        <el-button @click="selectDingUsers('assessUsers', 'assessUsersName')" style="margin-right:15px;">选择</el-button>
        <el-form-item label="订单状态：">
          <el-select style="width: 150px;" v-model="status" placeholder="请选择">
            <el-option
              v-for="item in orderStatusList2" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售时间：">
          <el-date-picker
            v-model="datarange"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchItem(true)">查询</el-button>
          <el-button v-if="isTeamer || isManager" type="primary" @click="openDialog()">录入</el-button>
          <el-button type="primary" @click="exportExcel()">导出</el-button>
          <el-button @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-table :height="tableHeight" ref="table" :data="tableData"  border style="width: 100%;overflow-x: auto;" >
          <el-table-column label="订单号" fixed prop="orderNo" min-width="180" align="center"></el-table-column>
          <el-table-column label="销售人员" prop="saleName" min-width="100" align="center"></el-table-column>
          <el-table-column label="折前销售金额($)" prop="saleValueBd" min-width="130" align="center"></el-table-column>
          <el-table-column label="折后销售金额($)" prop="saleValue" min-width="130" align="center"></el-table-column>
          <el-table-column label="类型" prop="type" min-width="100" align="center"></el-table-column>
          <el-table-column label="销售时间" prop="saleDate" min-width="180" align="center"></el-table-column>
          <el-table-column label="客户" prop="customerName" min-width="100" align="center"></el-table-column>
          <el-table-column label="客户等级" prop="customerLevel" min-width="100" align="center"></el-table-column>
          <el-table-column label="客户年限" prop="ageLimit" min-width="100" align="center"></el-table-column>
          <el-table-column label="国家" prop="countryName" min-width="100" align="center"></el-table-column>
          <el-table-column label="操作人" prop="opUser" min-width="100" align="center"></el-table-column>
          <el-table-column label="操作时间" prop="opDate" min-width="180" align="center"></el-table-column>
          <el-table-column label="备注" prop="remark" min-width="180" align="center"></el-table-column>
          <el-table-column v-if="isTeamer || isManager" label="操作" min-width="80" align="center">
            <template slot-scope="scope">
              <el-button @click="openDialog(scope.row)" type="text" size="small">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <el-dialog :fullscreen="true" :visible.sync="customerDialog" :show-close="false">
      <div slot="title">
        <h2 style="text-align:center;margin-bottom:0;">录入B2B订单</h2>
      </div>
      <div class="form-wrapper">
        <el-button type="info" class="back-btn" icon="el-icon-back" circle @click="customerDialog = false;"></el-button>
        <el-form ref="form" :model="customForm" label-width="200px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="订单号">
                <el-input v-model="customForm.orderNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="团队">
                 <el-select :disabled="!!customForm.id" v-model="customForm.teamId" placeholder="请选择团队">
                  <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="客户">
                <el-select
                  v-model="customForm.customerId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入客户名称、编号(最少输入2个字母)"
                  :remote-method="remoteMethod"
                  :loading="loading">
                  <el-option
                    v-for="item in custormerList"
                    :key="item.id"
                    :label="item.name + '（' +  item.code + '）（' + item.countryName + '）' "
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="订单状态">
                <el-select ref="labelSelected" :filterable="true" v-model="customForm.status" placeholder="请选择订单状态">
                  <el-option v-for="item in orderStatusList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="customForm.status !== 0">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="折前销售金额">
                <el-input v-model="customForm.saleValueBd"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="折后销售金额">
                <el-input v-model="customForm.saleValue"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="销售员">
                <el-tooltip style="width: calc(100% - 80px)" class="item" effect="dark" :disabled="customForm.saleName.length === 0" :content="customForm.saleName" placement="bottom">
                  <el-input @click="selectDingUsers2()" placeholder="请选择人员" v-model="customForm.saleName" :disabled="true"></el-input>
                </el-tooltip>
                <el-button :disabled="!!customForm.id" @click="selectDingUsers2()">选择</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="销售日期">
                <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="customForm.saleDate" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="备注">
                <el-input v-model="customForm.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="saveForm">录入</el-button>
            <el-button @click="customerDialog = false">关闭</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import formUtil from '@/utils/formUtil'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'

  export default {
    data () {
      return {
        pageSize: 10,
        page:1,
        totalPage: 0,
        customerId:'',
        datarange: '',
        pi: false,
        po: false,
        countryData: [],
        tableData: [],
        assessUsers: [],
        assessUsersName: '',
        customForm: {
          orderNo: '',
          teamId: '',
          saleValueBd: '',
          saleValue: '',
          customerId: '',
          status: '',
          remark: '',
          saleDate: '',
          saleName: '',
          saleId: ''
        },
        formVerify: {
          orderNo: '请输入订单号',
          teamId: '请选择团队',
          saleValueBd: '请输入折前销售金额',
          saleValue: '请输入折后销售金额',
          customerId: '请输入客户',
          status: '请选择订单状态',
          saleId: '请选择销售员',
          saleDate: '请选择销售日期'
        },
        customerDialog: false,
        teamList: [],
        loading:false,
        custormerList: [],
        orderStatusList2: [{
          id: '',
          name: '全部'
        },{
          id: 1,
          name: '已售'
        },{
          id: 0,
          name: '预售'
        },{
          id: -1,
          name: '退款'
        }],
        orderStatusList: [{
          id: 1,
          name: '已售'
        },{
          id: 0,
          name: '预售'
        },{
          id: -1,
          name: '退款'
        }],
        isTeamer: false,
        tableHeight: window.tableHeight,
        status: '',
        currentBelongTeam: ''
      }
    },
    activated() {
      this.tableHeight = document.documentElement['clientHeight'] - 270
      window.onresize = () => {
        this.tableHeight = document.documentElement['clientHeight'] - 270
      }
    },
    mixins: [dingMixin],
    computed: {
      isManager() {
        return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1265175017173348354')
      }
    },
    async mounted(){
      this.customerId = this.$route.query.customerId
      this.teamList = await this.$httpN.postQ('mpb/b2bteam/list');
      this.searchItem(true);
      this.teamList.forEach((item) => {
        let managerIdArr = item.managerId.split(',')
        let membersIdArr = item.membersId.split(',')
        if(managerIdArr.includes(this.userInfo.dingId) || membersIdArr.includes(this.userInfo.dingId)) {
          this.isTeamer = true;
          this.currentBelongTeam = item.id;
        }
      })
    },
    methods: {
      async openDialog(item) {
        if(item) {
          let editData = formUtil.deepCopy(item);
          this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: item.customerName});
          this.customForm = editData;
        }else{
          formUtil.resetData(this.customForm);
          this.customForm.status = '';
          if(this.currentBelongTeam) {
            this.customForm.teamId = this.currentBelongTeam;
          };
          this.customForm.saleName = this.userInfo.realName;
          this.customForm.saleId = this.userInfo.dingId;
        }
        this.customerDialog = true;
      },
      async remoteMethod(query) {
        if (query !== '' && query.length >= 2) {
          this.loading = true;
          this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: query});
          this.loading = false;
        } else {
          this.options = [];
        }
      },
      selectDingUsers(arr, showName){
        this.complexPicker(1, [], this[arr]).then((data)=>{
          this[arr] = data[0].emplId;
          this[showName] = data[0].name;
        })
      },
      selectDingUsers2(){
        this.complexPicker(1, [], [this.customForm.saleId]).then((data)=>{
          this.customForm.saleId = data[0].emplId;
          this.customForm.saleName = data[0].name;
        })
      },
      async searchItem(init) {
        if(init){
          this.page = 1;
        }
        let data = await this.$httpN.postQ('mpb/mpbsaleb2b/list',{
          beginDate: this.datarange? this.datarange[0]: '',
          endDate: this.datarange? this.datarange[1]: '',
          status: this.status,
          saleId: this.assessUsers? this.assessUsers: '',
          customerId: this.customerId,
          page: this.page,
          limit: this.pageSize
        })
        this.tableData = data.list
        this.totalPage = data.totalCount
      },
      resetSearch() {
        this.customerId = ''
        this.datarange = '';
        this.pi = false;
        this.po = false;
        this.assessUsers = '';
        this.assessUsersName = ''
      },
      sizeChangeHandle(limit) {
        this.pageSize = limit;
        this.searchItem(true);
      },
      currentChangeHandle(page) {
        this.page = page;
        this.searchItem();
      },
      async saveForm(){
        if(this.customForm.status === 0){
          this.customForm.saleValueBd = 0;
          this.customForm.saleValue = 0;
        }
        if(!formUtil.verifyData(this.customForm, this.formVerify)) return;
        let postForm = {
          orderNo: this.customForm.orderNo,
          teamId: this.customForm.teamId,
          saleValueBd: this.customForm.saleValueBd,
          saleValue: this.customForm.saleValue,
          customerId: this.customForm.customerId,
          status: this.customForm.status,
          remark: this.customForm.remark,
          saleDate: this.customForm.saleDate,
          saleId: this.customForm.saleId
        }
        if(this.customForm.id) postForm.id = this.customForm.id;
        if(!await this.$httpN.postB('mpb/mpbsaleb2b/save', postForm,false)) return;
        this.customerDialog = false;
        formUtil.submitSuccess('保存成功');
        this.searchItem(true);
      },
      removeItem(id) {
        formUtil.submitConfirm('此操作将永久删除该记录, 是否继续?', async ()=> {
          if(!await this.$httpN.postB('mpb/mpbsaleb2b/delete', [id], false)) return;
          formUtil.submitSuccess('删除成功');
          this.searchItem(true)
        })
      },
      async exportExcel() {
        if(!this.datarange[0] || !this.datarange[1]) return this.$message.error('请选择开始时间和结束时间')
        let data = await this.$httpN.get('mpb/mpbsaleb2b/export', {
          beginDate: this.datarange? this.datarange[0]: '',
          endDate: this.datarange? this.datarange[1]: '',
          saleId: this.assessUsers? this.assessUsers: '',
          status: this.status,
        }, 'blob')

        this.downFile(data, `B2B订单.xls`);
      },
      downFile(blob, fileName) {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

  .form-wrapper .el-select.el-select--medium{
    width: 100%;
  }
  .form-wrapper{
    width: 70%;
    min-width: 990px;
    margin: 0 auto;
    padding: 70px;
    padding-top: 10px;
    padding-left:0;
    position:relative;
  }
  .status-line{
    position:fixed;
    top: 200px;
    right: 140px;
    height: 240px;
  }
  .notice{
    margin-top:10px;
    color:red;
    padding-left:120px;
  }
  .back-btn{
    position: fixed;
    top: 50px;
    left: 50px;
  }
</style>
